<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="$t('table.email')" v-model="listQuery.email" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button> -->
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleMulDelete">{{ $t('table.batch_delete') }}</el-button>
      <el-button v-waves class="filter-item" type="success" icon="el-icon-download"  @click="onDownLoad">{{ $t('table.download') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
      style="width: 100%;">
      <el-table-column
        type="selection"
        width="35">
      </el-table-column>
      <el-table-column :label="$t('table.id')" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.first_name')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.first_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.last_name')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.last_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.email')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.contact')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.contact }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.created_at')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.updated_at')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button> -->
          <el-button size="mini" type="danger" @click="deleteData(scope.row)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

  </div>
</template>

<script>
import { fetchList, fetchShow, fetchStore, fetchUpdate, fetchDelete, fetchBatchDelete } from '@/api/subscribe'
import waves from '@/directive/waves' // Waves directive
import { parseTime, urlEncode } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import i18n from '@/lang/index'

export default {
  name: 'Tag',
  components: { Pagination },
  directives: { waves },
  filters: {
    availableFilter(status) {
      const availableMap = [
        'danger',
        'success'
      ]
      return availableMap[status]
    }
  },
  data() {
    return {
      //gggglobe: this.$store.state.locale.global, // store例子
      activeName: 'first',
      isAvailable: 2,
      tableKey: 0,
      list: null,
      content: ``,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        available: 2,
        email: '',
        lang: i18n.locale,
      },
      subscribe_ids: [],
      availableOptions: [{ 'value': 2, 'name': i18n.t('table_element.available.all') }, { 'value': 1, 'name': i18n.t('table_element.available.on') }, {'value': 0, 'name': i18n.t('table_element.available.un') }],
      // areaOptions: [{ name : '中国香港', id: 1 }, { name : '中国大陆', id: 2 }],
      showReviewer: false,
      temp: {
        id: '',
        name: '',
        email: '',
        contact_no: '',
        company: '',
        message: '',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  computed: {
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        //console.log(response)
        var data = response.data
        this.list = data.data.data
        this.total = data.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: 'Successful operation',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        email: '',
        contact_no: '',
        company: '',
        message: '',
      }
    },
    handleCreate() {
      // store例子
      //let ll = ['cc', 'aa']
     // this.$store.dispatch('addLocale', ll)
     // this.gggglobe = this.$store.state.locale.global
     // console.log('global1', this.gggglobe)
      // store例子end
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          this.temp.lang = i18n.locale
          fetchStore(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Create Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lang = i18n.locale
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          fetchUpdate(this.temp.id, tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Success!',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      console.log(row);
      this.$notify({
        title: 'Success',
        message: 'Delete Success!',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    deleteData(row) {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchDelete(row.id).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          }
          
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleMulDelete() {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchBatchDelete({ subscribe_id: this.subscribe_ids }).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleSelectionChange(val) {
      val.forEach(element => {
        if (this.subscribe_ids.indexOf(element.id) == -1) {
          this.subscribe_ids.push(element.id)
        }
      })
    },
    onDownLoad() { //跳转下载页
      let query = urlEncode(this.listQuery)
      let url = process.env.BASE_API + '/admin/subscribe-export?1=1' + query
      window.open(url)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
